package xyz.xtt.schedule.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.xtt.user.api.dto.TblUserFundRecordDto;
import xyz.xtt.user.api.dto.UpdateFundSettledRequest;

/**
 * @author dale
 * @date 2025/2/27
 **/
@Service
@Slf4j
public class UserFundAccountService {
	@Autowired
	private InnerService innerService;

	public void checkAndSettleSellerAccount() {
		log.info("开始执行用户资金结算任务");
		Long lastId = null;
		int querySize = 20;
		int totalHandled = 0;
		int settleSuccess = 0;
		while (true) {
			List<TblUserFundRecordDto> records = innerService.getNeedSettleRecords(querySize, lastId);
			if (CollectionUtils.isEmpty(records)) {
				break;
			}
			for (TblUserFundRecordDto record : records) {
				try {
					Boolean updateResult = innerService.updateFundSettled(new UpdateFundSettledRequest(record.getId()));
					if (updateResult) {
						settleSuccess++;
					}
				} catch (Exception e) {
					log.error("updateSellerFundSettled failed. record:{}", JSONUtil.toJsonStr(record), e);
				}
				totalHandled++;
			}
			lastId = records.get(records.size() - 1).getId();
		}
		log.info("用户资金结算任务执行完毕，共处理{}条记录，其中结算成功{}条", totalHandled, settleSuccess);
	}
}
